package logic

import (
	"context"
	"fmt"
	"work_1/models"

	"work_1/shop_rpc/internal/svc"
	"work_1/shop_rpc/shop_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *shop_rpc.UserLoginRequest) (*shop_rpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	var user = models.User{
		UserPhone: in.UserPhone,
	}
	if models.Db.Where("user_phone = ?", user.UserPhone).Find(&user).Error != nil {
		return &shop_rpc.UserLoginResponse{}, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return &shop_rpc.UserLoginResponse{}, fmt.Errorf("账号不存在")
	}
	if user.UserPassword != in.UserPassword {
		return &shop_rpc.UserLoginResponse{}, fmt.Errorf("账号或密码错误")
	}
	get_code, _ := models.Rdb.Get(models.Ctx, "code_phone:"+in.UserPhone).Result()
	if get_code != in.Code {
		return &shop_rpc.UserLoginResponse{}, fmt.Errorf("验证码错误")
	}
	return &shop_rpc.UserLoginResponse{
		Id: int64(user.ID),
	}, nil
}
